import django_filters
from django.shortcuts import render
from rest_framework.filters import SearchFilter, OrderingFilter
from rest_framework.generics import GenericAPIView
from rest_framework.mixins import ListModelMixin, RetrieveModelMixin
from rest_framework.response import Response
from rest_framework.views import APIView

# Create your views here.
from rest_framework.viewsets import GenericViewSet

from app.goods.filters import GoodsFilter
from app.goods.models import Goods, GoodsCategory
from app.goods.pagination import GoodsPagination
from app.goods.serializers import GoodListSerializer, CategorySerializer

'''
    # 继承APIView实现视图类
    class GoodListView(APIView):
        # 定义对应HTTP请求方式的处理函数
    
        def get(self, request, format=None):
            # 先查询所有的商品信息
            goods = Goods.objects.all()
            # 要序列化queryset或对象列表而不是单个对象实例，您应该在实例化序列化器时传递many=True标志。
            # 然后可以传递要序列化的对象的queryset或列表。
            serializer_data = GoodListSerializer(goods, many=True)
            return Response(serializer_data.data)

    方法二：使用GenericAPIView结合扩展类实现视图类
    class GoodListView(GenericAPIView, ListModelMixin):
        queryset = Goods.objects.all()
        serializer_class = GoodListSerializer
    
        def get(self, request, *args, **kwargs):
            return self.list(request, *args, **kwargs)
'''


class GoodListView(GenericViewSet, ListModelMixin, RetrieveModelMixin):
    '''
        list:商品列表
        retrieve:商品详细信息

    '''
    queryset = Goods.objects.all()
    serializer_class = GoodListSerializer
    pagination_class = GoodsPagination
    filter_backends = [django_filters.rest_framework.DjangoFilterBackend,
                       SearchFilter, OrderingFilter]
    # filterset_fields = ['name', 'click_num']
    filterset_class = GoodsFilter
    search_fields = ['name', 'goods_desc']
    ordering_fields = ['shop_price']


class CategoryView(GenericViewSet, ListModelMixin, RetrieveModelMixin):
    '''
        list:
            商品分类列表
        retrieve:
            商品分类详情
    '''
    # 实现分级展示,
    
    queryset = GoodsCategory.objects.filter(category_type=1)
    serializer_class = CategorySerializer
    # pagination_class = GoodsPagination
